﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using elmah2.core.loggers;
using elmah2.core.data;
using System.Data;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Configuration;
using elmah2.core.encoders;

namespace elmah2.MySql
{
  public class MySqlLogger : DBLogger
  {
    public override IDbCommand GetCommand()
    {
      return new MySqlCommand();
    }

    public override IDbCommand GetErrorsCommand(int page, int numPerPage, int? app)
    {
      StringBuilder sb = new StringBuilder();
      MySqlCommand command = new MySqlCommand();
      sb.Append("SELECT *, (SELECT COUNT(*) FROM Errors as count) as Count FROM Errors ");

      if (app.HasValue)
      {
        sb.Append(" WHERE Application = @app");
        command.Parameters.AddWithValue("@app", app.Value);
      }

      sb.Append(" LIMIT @skip, @take");

      command.Parameters.AddWithValue("@skip", numPerPage * (page - 1));
      command.Parameters.AddWithValue("@take", numPerPage * (page));
      command.CommandText = sb.ToString();
      return command;
    }

    public override IDbConnection GetConnection()
    {
      return new MySqlConnection(_connectionString);
    }
  }
}
